<?php

    extract(extractPost(), EXTR_PREFIX_ALL, 'g');

    if(isset($g_name) && isset($g_users)){
        /*****  errors *****/
        $result = array();

        $group_exists = R::findOne('group',' name = ? ', array( $g_name ));

        if($group_exists) jsonErrorDie("Group whit this name already exists. Please use another name.");

        $g_users = json_decode($g_users, true);

        if (is_null($g_users)) jsonErrorDie("Json is not valid.");

        $users = R::loadAll('user', array_keys($g_users) );

        $kanbanMaster = null;
        $productOwner = null;
        $developer = [];
        foreach($users as $user) {
            if ($user->id == 0) {
                jsonErrorDie("Not all provided users exists");
            }

            foreach( $user->sharedRole as $role){
                if($role->id == 2 && in_array(2, $g_users[$user->id]))
                    $kanbanMaster = $user->id;
                if($role->id == 3 && in_array(3, $g_users[$user->id]))
                    $productOwner = $user->id;
                if($role->id == 4 && in_array(4, $g_users[$user->id]))
                    $developer[] = $user->id;
            }
        }

        if (is_null($kanbanMaster))
            jsonErrorDie("Kanban master does not exists");

        if (is_null($productOwner))
            jsonErrorDie("Product owner does not exists");

        /***** end errors ****/



        /* Create new group. */
        $g = R::dispense( 'group' );
        $g->name = $g_name;
        $g->nonActiveUsers = json_encode([]);
        $g->kanbanMaster = $kanbanMaster;
        $g->productOwner = $productOwner;
        $g->developers= json_encode($developer);
        $g_id = R::store( $g );

        //save many-to-many
        foreach($users as $user){
            $user->sharedGroupList[] = $g;

            //remember date added to group
            $date = R::isoDateTime();
            $ga = R::dispense('gactivity');
            $ga->user = $user;
            $ga->group = $g;
            $ga->dateFrom = $date;
            $ga->dateTo = $date;
            R::store($ga);
        }

        R::storeAll($users);

        if(isset($g_id)){
            $result["group_id"] = $g_id;
            $result["success"] = 'true';
            $result["message"] = 'Successfully created group';
            echo json_encode($result);
            die();
        }
    }

    jsonErrorDie("Problem occured while inserting group in database");
